package com.ybc.chinese.widget;

import android.app.ProgressDialog;
import android.content.Context;
import android.util.AttributeSet;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.ybc.chinese.R;
import com.ybc.chinese.utils.DialogUtil;

/**
 * <p><p/>
 * Created by Yubch on 17/1/18.
 */
public class MyWebView extends WebView {
    private Context mCtx;
    private ProgressDialog mRunningDialog;

    public MyWebView(Context context) {
        super(context);
        init(context);
    }

    public MyWebView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public MyWebView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    private void init(Context context) {
        mCtx = context;
        WebSettings webSettings = this.getSettings();
        //支持javascript
        webSettings.setJavaScriptEnabled(true);
        webSettings.setDomStorageEnabled(true);
        webSettings.setAppCacheMaxSize(1024 * 1024 * 8);
        String appCacheDir = context.getDir("cache", Context.MODE_PRIVATE).getPath();
        webSettings.setAppCachePath(appCacheDir);
        webSettings.setAllowFileAccess(true);
        webSettings.setAppCacheEnabled(true);
        webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
        // 设置可以支持缩放
        webSettings.setSupportZoom(true);
        // 设置出现缩放工具
        webSettings.setBuiltInZoomControls(true);
        //扩大比例的缩放
        webSettings.setUseWideViewPort(true);
        //自适应屏幕
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setUseWideViewPort(true);
        this.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (newProgress == 100) {
                    dismissRunningDialog();
                } else {
                    showRunningDialog();
                }
                super.onProgressChanged(view, newProgress);
            }
        });

        this.setWebViewClient(new WebViewClient(){
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }
        });
    }


    protected void showRunningDialog() {
        if (mRunningDialog == null) {
            mRunningDialog = DialogUtil.getProgressDialog(mCtx, R.string.running);
        }
        if (!mRunningDialog.isShowing()) {
            mRunningDialog.show();
        }

    }

    protected void dismissRunningDialog() {
        if (mRunningDialog != null && mRunningDialog.isShowing()) {
            mRunningDialog.dismiss();
        }
    }
}
